<?php

namespace app\admin\controller;

use think\Db;
use nsCms\Leftnav;
use app\common\model\Admin as Admins;
use app\common\model\AuthGroup;
use app\common\model\authRule;
use think\facade\Request;
use think\Validate;

class Admin extends Common
{
    //管理员列表
    public function adminList()
    {
//        echo "2222";die;
        if (Request::isAjax()) {
            $val = input('val');
            $url['val'] = $val;
            $this->assign('val', $val);
            $map = '';
            if ($val) {
                $map[] = ['username', 'like', "%" . $val . "%"];
            }
            //不是超管
            if (session('admin_id') != 1) {
                $map[] = ['id', '=', session('admin_id')];
            }
            $list = db('admin')->alias('a')
                ->join('auth_group ag', 'a.group_id = ag.id', 'left')
                ->field('a.*,ag.title')
                ->where($map)
                ->select();
            foreach ($list as &$v) {
                $v['last_time'] = empty($v['last_login']) ? '' : date('Y-m-d H:i:s', $v['last_login']);
            }
            return ['code' => 0, 'msg' => '获取成功!', 'data' => $list];
        }
        return view();
    }
    
    //更新管理员信息
    public function adminEdit()
    {
        if (request()->isPost()) {
            $data = input('post.');
            $msg = $this->validate($data, 'app\admin\validate\Admin');
            if ($msg != 'true') {
                return ['code' => 0, 'msg' => $msg];
            }
            if ($data['id'] > 0) {
                //用户名验证
                if ($data['username']) {
                    $map[] = ['id', '<>', $data['id']];
                    $map[] = ['username', '=', $data['username']];
                    $check_user = Admins::where($map)->find();
                    if ($check_user) {
                        return ['code' => 0, 'msg' => '用户已存在，请重新输入用户名!'];
                    }
                }
                //处理密码
                if (!empty($data['password'])) {
                    $data['password'] = input('post.password', '', 'md5');
                } else {
                    unset($data['password']);
                }
                Admins::update($data, ['id' => $data['id']]);
                if ($data['id'] == session('admin_id')) {
                    session('username', $data['username']);
                    $avatar = $data['avatar'] == '' ? '__PUBLIC__admin/images/0.jpg' : $data['avatar'];
                    session('avatar', $avatar);
                }
                return ['code' => 1, 'msg' => '管理员修改成功!', 'url' => url('adminList')];
            } else {
                $check_user = get(['username' => $data['username']]);
                if ($check_user) {
                    return ['code' => 0, 'msg' => '用户已存在，请重新输入用户名!'];
                }
                $data['password'] = input('post.password', '', 'md5');
                $data['create_time'] = time();
                $data['last_ip'] = request()->ip();
                //单独验证密码
                $checkPwd = Validate::make([input('post.password') => 'require']);
                if (false === $checkPwd) {
                    return ['code' => 0, 'msg' => '密码不能为空！'];
                }
                //添加
                if (Admins::create($data)) {
                    return ['code' => 1, 'msg' => '管理员添加成功!', 'url' => url('adminList')];
                } else {
                    return ['code' => 0, 'msg' => '管理员添加失败!'];
                }
            }
        } else {

            $auth_group = AuthGroup::all();
            $id = $this->request->get('id');


//            $info = $admin->getInfo(input('id'));
            $info = Db("admin")->get(input('id'));


            $this->assign('info', json_encode($info));
            $this->assign('authGroup', $auth_group);

            $this->assign('title', input('id', 0) > 0 ? lang('edit') : lang('add') . lang('admin'));


            return view('adminForm');
        }
    }
    
    //删除管理员
    public function adminDel()
    {
        $admin_id = input('post.id');
        if (session('admin_id') == 1) {
            Admins::where('admin_id', '=', $admin_id)->delete();
            return ['code' => 1, 'msg' => '删除成功!'];
        } else {
            return ['code' => 0, 'msg' => '您没有删除管理员的权限!'];
        }
    }
    
    //修改管理员状态
    public function adminState()
    {
        $id = input('post.id');
        $status = input('post.status');
        db('admin')->where('id=' . $id)->update(['status' => $status]);
        $result['code'] = 1;
        $result['info'] = '用户状态修改成功!';
        $result['url'] = url('adminList');
        return $result;
    }
    
    //管理组
    public function adminGroup()
    {
        if (request()->isPost()) {
            $list = AuthGroup::all();
            return ['code' => 0, 'msg' => '获取成功!', 'data' => $list];
        }
        return view();
    }
    
    //添加分组
    public function groupAdd()
    {
        $data = input('post.');
        $data['create_time'] = time();
        AuthGroup::create($data);
        return ['msg' => '用户组添加成功!', 'url' => url('adminGroup'), 'code' => 1];
    }
    
    //修改分组
    public function groupEdit()
    {
        $data = input('post.');
        $where['id'] = $data['id'];
        AuthGroup::update($data, $where);
        return ['code' => 1, 'msg' => '用户组修改成功!', 'url' => url('adminGroup')];
    }
    
    //删除分组
    public function groupDel()
    {
        AuthGroup::where('id', '=', input('id'))->delete();
        return ['code' => 1, 'msg' => '删除成功!'];
    }
    
    //分组规则
    public function groupAccess()
    {
        $nav = new Leftnav();
        $admin_rule = db('auth_rule')->field('id,pid,title')->order('sort asc')->select();
        $rules = db('auth_group')->where('id', input('id'))->value('rules');
        $arr = $nav->auth($admin_rule, $pid = 0, $rules);
        $arr[] = [
            "id"    => 0,
            "pid"   => 0,
            "title" => "全部",
            "open"  => true,
        ];
        $this->assign('data', json_encode($arr, true));
        return $this->fetch();
    }
    
    //分组配置
    public function groupSetAccess()
    {
        $rules = input('post.rules');
        if (empty($rules)) {
            return ['msg' => '请选择权限!', 'code' => 0];
        }
        $data = input('post.');
        $where['id'] = $data['group_id'];
        if (AuthGroup::update($data, $where)) {
            return ['msg' => '权限配置成功!', 'url' => url('adminGroup'), 'code' => 1];
        } else {
            return ['msg' => '保存错误', 'code' => 0];
        }
    }
    
    //权限规则
    public function adminRule()
    {
        if (request()->isPost()) {
            $arr = cache('authRuleList');
            if (!$arr) {
                $arr = Db::name('authRule')->order('pid asc,sort asc,id asc')->select();
                foreach ($arr as $k => $v) {
                    $arr[$k]['lay_is_open'] = false;
                }
                cache('authRuleList', $arr, 3600);
            }
            return ['code' => 0, 'msg' => '获取成功!', 'data' => $arr, 'is' => true, 'tip' => '操作成功'];
        }
        return view();
    }
    
    //删除无效规则
    public function clear()
    {
        $arr = Db::name('authRule')->where('pid', 'neq', 0)->select();
        foreach ($arr as $k => $v) {
            $p = Db::name('authRule')->where('id', $v['pid'])->find();
            if (!$p) {
                Db::name('authRule')->where('id', $v['id'])->delete();
            }
        }
        cache('authRule', null);
        cache('authRuleList', null);
        $this->success('清除成功');
    }
    
    //添加规则
    public function ruleAdd()
    {
        if (request()->isPost()) {
            $data = input('post.');
            $data['create_time'] = time();
            authRule::create($data);
            cache('authRule', null);
            cache('authRuleList', null);
            return ['code' => 1, 'msg' => '权限添加成功!', 'url' => url('adminRule')];
        } else {
            $nav = new Leftnav();
            $arr = cache('authRuleList');
            if (!$arr) {
                $authRule = authRule::all(function($query) {
                    $query->order('sort', 'asc');
                });
                $arr = $nav->menu($authRule);
                cache('authRuleList', $arr, 3600);
            }
            $this->assign('admin_rule', $arr);//权限列表
            return $this->fetch();
        }
    }
    
    //规则排序
    public function ruleOrder()
    {
        $auth_rule = db('auth_rule');
        $data = input('post.');
        if ($auth_rule->update($data) !== false) {
            cache('authRuleList', null);
            cache('authRule', null);
            return ['code' => 1, 'msg' => '排序更新成功!', 'url' => url('adminRule')];
        } else {
            return ['code' => 0, 'msg' => '排序更新失败!'];
        }
    }
    
    //设置权限菜单显示或者隐藏
    public function ruleState()
    {
        $id = input('post.id');
        $menustatus = input('post.menustatus');
        if (db('auth_rule')->where('id=' . $id)->update(['menustatus' => $menustatus]) !== false) {
            cache('authRule', null);
            cache('authRuleList', null);
            return ['status' => 1, 'msg' => '设置成功!'];
        } else {
            return ['status' => 0, 'msg' => '设置失败!'];
        }
    }
    
    //设置权限是否验证
    public function ruleTz()
    {
        $id = input('post.id');
        $authopen = input('post.authopen');
        if (db('auth_rule')->where('id=' . $id)->update(['authopen' => $authopen]) !== false) {
            cache('authRule', null);
            cache('authRuleList', null);
            return ['status' => 1, 'msg' => '设置成功!'];
        } else {
            return ['status' => 0, 'msg' => '设置失败!'];
        }
    }
    
    //权限删除
    public function ruleDel()
    {
        authRule::destroy(['id' => input('param.id')]);
        cache('authRule', null);
        cache('authRuleList', null);
        return ['code' => 1, 'msg' => '删除成功!'];
    }
    
    //权限编辑
    public function ruleEdit()
    {
        if (request()->isPost()) {
            $data = input('post.');
            if (authRule::update($data)) {
                cache('authRule', null);
                cache('authRuleList', null);
                return json(['code' => 1, 'msg' => '保存成功!', 'url' => url('adminRule')]);
            } else {
                return json(['code' => 0, 'msg' => '保存失败！']);
            }
        } else {
            $admin_rule = authRule::get(function($query) {
                $query->where(['id' => input('id')])->field('id,href,title,icon,sort,menustatus');
            });
            $this->assign('rule', $admin_rule);
            return $this->fetch();
        }
    }
}